﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cyss.Core.Repository.SqlSugar
{
    public class PagedList<T> : List<T>, IPagedList<T>
    {
        public PagedList(ISugarQueryable<T> source, BaseSearchModel model)
        {
            if (!model.getOnlyData)
            {
                var total = source.Count();
                this.TotalCount = total;
                this.TotalPages = total / model.pageSize;

                if (total % model.pageSize > 0)
                    TotalPages++;
            }


            this.PageSize = model.pageSize;
            this.PageIndex = model.pageSize-1;
            if (model.getOnlyTotalCount)
                return;

            if (model.OrderByFields != null && model.OrderByFields.Count > 0)
            {
                //source = source.OrderBy.OrderConditions(model.OrderByFields);
            }
            this.AddRange(source.Skip((model.pageIndex-1) * model.pageSize).Take(model.pageSize).ToList());
        }

        /// <summary>
        /// Page index
        /// </summary>
        public int PageIndex { get; }

        /// <summary>
        /// Page size
        /// </summary>
        public int PageSize { get; }

        /// <summary>
        /// Total count
        /// </summary>
        public int TotalCount { get; }

        /// <summary>
        /// Total pages
        /// </summary>
        public int TotalPages { get; }

        /// <summary>
        /// Has previous page
        /// </summary>
        public bool HasPreviousPage => PageIndex > 0;

        /// <summary>
        /// Has next page
        /// </summary>
        public bool HasNextPage => PageIndex + 1 < TotalPages;
    }
}
